window.onload = function () {
    listOrder();
}

function listOrder() {
    var xhr = new XMLHttpRequest();

    var username = getUserNameFromCookie();

    xhr.open("GET", "http://localhost:8080/listOrder?username=" + username, true);

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                showOrder(xhr.responseText);
            }
            else {
                console.error(xhr.status);
            }
        }
    }

    xhr.send();
}

function showOrder(json) {
    var orders = JSON.parse(json);
    console.log(orders);

    var list = document.getElementById("list");

    orders.forEach(order => {
        var div = document.createElement("div");
        div.className = "order";

        var itemList = "";
        var totalPrice = 0;

        order.items.forEach(item => {
            var total = parseFloat(item.price) * parseFloat(item.amount);
            itemList += "<div class='item'><table><tr><th rowspan='2'><img src='img/"
                + item.img
                + "'></th><td>名称</td><td>单价</td><td>数量</td><td>总价</td></tr><tr><td>"
                + item.title + "</td><td>"
                + item.price + "</td><td>"
                + item.amount + "</td><td>￥"
                + total.toFixed(2) + "</td></tr></table></div>";
            totalPrice += total;
        });

        var date = new Date(order.date);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        date = year + '-' + month + '-' + day;


        div.innerHTML = `<p id="orderNum">订单号：<span>`
            + order.id
            + `</span></p><p id="orderDate">日期：<span>`
            + date + `</span></p>`
            + itemList + `<p>总金额：￥`
            + totalPrice + `</p>`;

        list.appendChild(div);
    });
}